Update statistics

If index rebuilding is undesirable at this time due to the additional database impact, the alternative plan is to update statistics. To update statistics, run the following script for each table that requires and udpate:

UPDATE STATISTICS [table name here] WITH FULLSCAN ;

Reset plan cache for this specific query. Use sql_handle which was already found.

DBCC FREEPROCCACHE (..here sql_handle...)

 

Updating statistics usually causes queries to recompile. We recommend to reset plan cache to make it certain and immediate. Without this step, SQL Server may delay recompilation.

DECLARE @tb_name nvarchar(255)

SET @tb_name ='inv_wq'

SELECT

convert(NVARCHAR(800),'ALTER INDEX ' + i.name + ' ON ' +@tb_name + ' REORGANIZE; UPDATE STATISTICS '+ @tb_name +' ' +i.name+' WITH FULLSCAN ')

as alter_statements

FROM sys.indexes AS i

JOIN sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED') AS ind_st

ON ind_st.object_id = i.object_id AND ind_st.index_id = i.index_id

WHERE i.object_id = OBJECT_ID(@tb_name)

and i.index_id>0

and avg_fragmentation_in_percent>10

order by avg_fragmentation_in_percent desc